<template>
    <div class="category-management-container">
        <div class="header-card">
            <h2>商品分类管理</h2>
            <p>管理商品分类，商家可选择对应分类</p>
        </div>

        <el-card class="table-card" shadow="never">
            <div class="toolbar">
                <el-button type="primary" @click="addCategory" icon="el-icon-plus">新增分类</el-button>
                <div class="search-area">
                    <el-select v-model="filterShopId" placeholder="请选择商家" clearable
                        style="width: 200px; margin-left: 20px;" @change="fetchData">
                        <el-option label="全部商家" :value="null"></el-option>
                        <el-option label="平台通用分类" value="0"></el-option>
                        <el-option v-for="shop in shopOptions" :key="shop.id" :label="shop.shop_name"
                            :value="shop.id.toString()" />
                    </el-select>

                    <el-input v-model="searchKeyword" placeholder="搜索分类名称" style="width: 200px; margin-left: 20px;"
                        clearable @keyup.enter="fetchData">
                        <template #append>
                            <el-button icon="el-icon-search" @click="fetchData"></el-button>
                        </template>
                    </el-input>
                </div>
            </div>

            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="name" label="分类名称" min-width="180" />
                <el-table-column label="分类图片" width="150" align="center">
                    <template #default="scope">
                        <el-image v-if="scope.row.image_url" :src="getImageUrl(scope.row.image_url)"
                            class="category-image" :preview-src-list="[getImageUrl(scope.row.image_url)]" fit="cover"
                            hide-on-click-modal>
                            <template #error>
                                <div class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </template>
                        </el-image>
                        <div v-else class="no-image">
                            <i class="el-icon-picture"></i>
                            <span>暂无图片</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="shop_name" label="所属商家" min-width="180" />
                <el-table-column label="商家ID" width="100" align="center">
                    <template #default="scope">{{ scope.row.shop_id === 0 ? '平台通用' : scope.row.shop_id }}</template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="editCategory(scope.row)" plain
                            round>编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteCategory(scope.row)" plain
                            round>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleDialogClose">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" label-position="right">
                <el-form-item label="分类名称:" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入分类名称" />
                </el-form-item>

                <el-form-item label="所属商家:" prop="shop_id">
                    <el-select v-model="formData.shop_id" placeholder="请选择所属商家" clearable style="width: 100%">
                        <el-option label="平台通用分类" :value="0"></el-option>
                        <el-option v-for="shop in shopOptions" :key="shop.id" :label="shop.shop_name"
                            :value="shop.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="分类图片:">
                    <el-upload class="image-uploader" action="http://localhost:8889/api/upload/category" method="post"
                        :show-file-list="false" :on-success="handleImageSuccess" :before-upload="beforeImageUpload"
                        name="file">
                        <img v-if="formData.image_url" :src="getImageUrl(formData.image_url)" class="image-preview" />
                        <el-icon v-else class="image-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)
const isAddMode = ref(true)
const filterShopId = ref(null) // 商家筛选条件

const baseUrl = 'http://localhost:8889' // 后端服务地址

// 商家选项
const shopOptions = ref([])

const formData = reactive({
    id: '',
    name: '',
    image_url: '',
    shop_id: 0
})

const formRules = {
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
    ],
    shop_id: [
        { required: true, message: '请选择所属商家', trigger: 'change' }
    ]
}

const dialogTitle = computed(() => {
    return isAddMode.value ? '新增分类' : '编辑分类'
})

// 获取图片完整URL
const getImageUrl = (url) => {
    if (!url) return ''
    if (url.startsWith('http')) return url
    return `${baseUrl}${url}`
}

// 获取商家列表
const fetchShopOptions = async () => {
    try {
        const response = await axios.get(`${baseUrl}/api/admin/business/list`, {
            params: {
                page: 1,
                pageSize: 1000 // 获取所有商家
            }
        })

        if (response.data.code === 200) {
            shopOptions.value = response.data.data
        }
    } catch (error) {
        ElMessage.error('获取商家列表失败: ' + error.message)
    }
}

const fetchData = async () => {
    loading.value = true
    try {
        const response = await axios.get(`${baseUrl}/api/admin/category/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                name: searchKeyword.value,
                ...(filterShopId.value !== null && { shop_id: filterShopId.value })
            }
        })

        if (response.data.code === 200) {
            // 处理商家名称显示
            const categories = response.data.data.map(category => {
                if (category.shop_id === 0) {
                    return { ...category, shop_name: '平台通用' }
                } else {
                    const shop = shopOptions.value.find(s => s.id === category.shop_id)
                    return { ...category, shop_name: shop ? shop.shop_name : '未知商家' }
                }
            })

            tableData.value = categories
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取分类列表失败')
        }
    } catch (error) {
        ElMessage.error('获取分类列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const addCategory = () => {
    isAddMode.value = true
    resetForm()
    dialogVisible.value = true
}

const editCategory = (row) => {
    isAddMode.value = false
    Object.assign(formData, row)
    dialogVisible.value = true
}

const deleteCategory = (row) => {
    // 平台通用分类也可以删除
    ElMessageBox.confirm(
        `确定要删除分类"${row.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.delete(`${baseUrl}/api/admin/category/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('删除成功')
                fetchData()
            } else {
                ElMessage.error(response.data.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error('删除失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消删除
    })
}

const resetForm = () => {
    Object.assign(formData, {
        id: '',
        name: '',
        image_url: '',
        shop_id: 0
    })
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const handleDialogClose = (done) => {
    dialogVisible.value = false
    resetForm()
}

const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                let response
                if (isAddMode.value) {
                    // 新增分类
                    response = await axios.post(`${baseUrl}/api/admin/category/addCategory`, {
                        name: formData.name,
                        image_url: formData.image_url,
                        shop_id: formData.shop_id
                    })
                } else {
                    // 编辑分类
                    response = await axios.put(`${baseUrl}/api/admin/category/${formData.id}`, {
                        name: formData.name,
                        image_url: formData.image_url,
                        shop_id: formData.shop_id
                    })
                }

                if (response.data.code === 200) {
                    ElMessage.success(isAddMode.value ? '新增分类成功' : '编辑分类成功')
                    dialogVisible.value = false
                    fetchData()
                } else {
                    ElMessage.error(response.data.message || (isAddMode.value ? '新增分类失败' : '编辑分类失败'))
                }
            } catch (error) {
                ElMessage.error((isAddMode.value ? '新增分类失败' : '编辑分类失败') + ': ' + error.message)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

const handleImageSuccess = (response, uploadFile) => {
    if (response.code === 200) {
        formData.image_url = response.data.category_img_url
        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.message || '图片上传失败')
    }
}

const beforeImageUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('分类图片只能是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('分类图片大小不能超过 5MB!')
        return false
    }
    return true
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchShopOptions()
    fetchData()
})
</script>

<style scoped>
.category-management-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.category-image {
    width: 80px;
    height: 80px;
    border-radius: 6px;
}

.image-slot {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    color: #c0c4cc;
}

.image-slot i {
    font-size: 24px;
    margin-bottom: 5px;
}

.no-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    color: #c0c4cc;
    font-size: 12px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
}

.no-image i {
    font-size: 20px;
    margin-bottom: 3px;
}

.image-uploader .image-preview {
    width: 150px;
    height: 150px;
    display: block;
    border-radius: 6px;
}

.image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.image-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}
</style>